﻿using UnityEngine;
using System.Collections;

public class StreamLoader : Loader
{
	WWW m_request = null;

	public StreamLoader()
		: base(Loader.LoaderType.STREAM)
	{

	}

	protected override void Reset()
	{
		base.Reset();

		if (m_request != null)
		{
			m_request.Dispose();
			m_request = null;
		}
	}

	public override void Load()
	{
		base.Load();

		if (m_async)
		{
            string path = m_path;

            bool hasHead = (bool)m_param;
            if (!hasHead) {
                path = FileHelper.GetFullPath (path);
            }

            m_request = new WWW (path);
		}
		else
		{
			object data = null;
			try
			{
                data = FileHelper.ReadBytesFromFile(m_path);
			}
			catch(System.Exception e)
			{
				Debuger.LogError(e.Message);
			}
			finally
			{
				OnLoadCompleted(data);
				data = null;
			}
		}
	}

	public override void Update(float dt)
	{
		if (m_state == LoaderState.LOADING)
		{
			if (m_request == null)
			{
				OnLoadCompleted(null);
			}
			else if (!string.IsNullOrEmpty(m_request.error))
			{
				Debuger.LogError(m_request.error);
				OnLoadCompleted(null);
			}
			else if (m_request.isDone)
			{
				OnLoadCompleted(m_request.bytes);
			}
			else
			{
				OnLoadProgress(m_request.progress);
			}
		}
	}
}